import router from '@/router'
import store from '@/store'
import axios from 'axios'
// 导出基准地址，原因：其他地方不是通过axios发请求的地方用上基准地址
export const baseURL = 'http://apipc-xiaotuxian-front.itheima.net/'
const request = axios.create({
  baseURL,
  timeout: 5000
})
request.interceptors.request.use(
  (config) => {
    const { profile } = store.state.user
    if (profile.token) {
      // 3. 设置token
      config.headers.Authorization = `Bearer ${profile.token}`
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
request.interceptors.response.use(
  (res) => {
    return res.data
  },
  (err) => {
    if (err.response && err.response.status === 401) {
      // 清空store数据
      store.commit('user/setUser', {})
      const fullPath = encodeURIComponent(router.currentRoute.value.fullPath)
      router.push('/login/?redirectUrl=' + fullPath)
    }
    return Promise.reject(err)
  }
)
// 请求函数
export default (url, method, submitData) => {
  return request({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
